<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量导入项目"
    width="600px"
    class="custom-dialog"
  >
    <div class="flex flex-col gap-4">
      <!-- 搜索表单 -->
      <div v-if="!showResults" class="search-form">
        <div class="mb-4">
          <el-alert
            type="info"
            show-icon
            :closable="false"
            class="custom-alert"
          >
            <template #title>
              <span class="font-medium">批量导入</span>
            </template>
            <div class="text-sm">
              使用此工具从GitHub搜索并批量导入AI代理和MCP项目。系统将自动过滤重复项目。
            </div>
          </el-alert>
        </div>
        
        <div class="mb-4">
          <label class="block text-sm font-medium mb-1 text-gray-300">搜索关键词</label>
          <el-input 
            v-model="searchQuery" 
            placeholder="输入搜索关键词，如'AI Agent MCP'"
            class="custom-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="flex justify-end">
          <div class="mb-4">
            <label class="block text-sm font-medium mb-1 text-gray-300">&nbsp;</label>
          </div>
          <el-button 
            type="primary" 
            class="custom-button"
            :loading="isLoading" 
            :disabled="searchQuery.trim() === ''"
            @click="handleSearch"
          >
            <el-icon><Search /></el-icon>
            搜索项目
          </el-button>
        </div>
      </div>
      
      <!-- 结果展示 -->
      <div v-else class="results-container">
        <div class="mb-4">
          <el-alert
            :type="error ? 'error' : 'success'"
            show-icon
            :closable="false"
            class="custom-alert"
          >
            <template #title>
              <span class="font-medium">
                {{ error ? '搜索出错' : `找到 ${totalFound} 个项目` }}
              </span>
            </template>
            <div class="text-sm">
              {{ error ? error : status }}
            </div>
          </el-alert>
        </div>
        
        <div v-if="isLoading" class="py-4">
          <div class="mb-2 text-sm text-center text-gray-300">{{ status }}</div>
          <el-progress :percentage="progress" color="#8b5cf6" />
        </div>
        
        <div v-else-if="searchResults.length > 0" class="mb-4">
          <div class="text-sm mb-2 text-gray-300">可添加的项目 ({{ searchResults.length }})</div>
          <el-scrollbar height="200px" class="custom-scrollbar">
            <ul class="m-0 p-0 list-none">
              <li 
                v-for="(repo, index) in searchResults" 
                :key="index"
                class="p-3 border-b border-gray-700 last:border-0 hover:bg-gray-700"
              >
                <div class="flex flex-col w-full">
                  <div class="flex items-center">
                    <el-checkbox
                      :checked="selectedIndices.includes(index)"
                      @change="toggleSelect(index)"
                      size="small"
                    >
                      <div style="font-size: 1rem; font-weight: 600; color: #e5e7eb;">{{ repo.name }}</div>
                    </el-checkbox>
                  </div>
                  <div class="flex items-center ml-8 mt-1">
                    <div class="text-xs text-gray-400">
                      <el-icon class="text-purple-400"><Link /></el-icon>
                      {{ repo.githubUrl }}</div>
                  </div>
                </div>
              </li>
            </ul>
          </el-scrollbar>
        </div>
        
        <div v-else-if="!isLoading && !error" class="py-4 text-center">
          <el-empty description="未找到新项目" :image-size="80" />
        </div>
        
        <div class="flex justify-between">
          <el-button class="custom-button-secondary" @click="resetState">
            <el-icon><Back /></el-icon>
            返回搜索
          </el-button>
          <el-button 
            type="primary" 
            class="custom-button"
            :disabled="selectedIndices.length === 0 || isLoading"
            @click="handleAddProjects"
          >
            <el-icon><Upload /></el-icon>
            添加 {{ selectedIndices.length }} 个项目
          </el-button>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="flex justify-end">
        <el-button class="custom-button-secondary" @click="handleCancel">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useMcpApiService } from '../../services/McpApiService'
import { Search, InfoFilled, Link, Key, Plus, ArrowLeft, Back, Upload } from '@element-plus/icons-vue'

// 属性和事件
const props = defineProps<{
  visible: boolean
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'projects-added', agents: any[]): void
}>()

// 服务引用
const mcpApiService = useMcpApiService()

// 状态管理
const dialogVisible = ref(false)
const isLoading = ref(false)
const githubToken = ref('')
const status = ref('')
const progress = ref(0)
const error = ref<string | null>(null)
const importedProjects = ref<any[]>([])
const showResults = ref(false)
const searchResults = ref<any[]>([])
const importedCount = ref(0)
const totalFound = ref(0)
const isFirstImport = ref(true)
const selectedIndices = ref<number[]>([])
const searchQuery = ref('AI Agent MCP')

// 监听可见性变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val
  if (val) {
    // 加载保存的GitHub Token
    const savedToken = localStorage.getItem('github_token')
    if (savedToken) {
      githubToken.value = savedToken
    }
    
    // 检查是否做过导入
    const hasImported = localStorage.getItem('has_imported_repos') === 'true'
    isFirstImport.value = !hasImported
  }
})

watch(() => dialogVisible.value, (val) => {
  emit('update:visible', val)
  if (!val) {
    // 如果有新项目添加，需要关闭时通知
    if (importedCount.value > 0) {
      emit('projects-added', importedProjects.value)
    }
  }
})

// 生命周期钩子
onMounted(() => {
  // 检查是否有保存的Token
  const savedToken = localStorage.getItem('github_token')
  if (savedToken) {
    githubToken.value = savedToken
  }
})

// 方法
const handleSearch = async () => {
  if (searchQuery.value.trim() === '') {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  isLoading.value = true
  progress.value = 0
  error.value = null
  importedProjects.value = []
  showResults.value = true
  searchResults.value = [] as any[]
  importedCount.value = 0
  
  try {
    // 保存GitHub Token到本地存储
    if (githubToken.value) {
      localStorage.setItem('github_token', githubToken.value)
    }
    
    status.value = '正在搜索GitHub仓库...'
    progress.value = 25
    
    // 获取现有项目以便过滤重复
    const existingProjects = await mcpApiService.getAllProjects()
    const existingUrls = existingProjects.map(project => project.githubUrl)
    
    status.value = '正在查询GitHub API...'
    progress.value = 50
    
    // 使用MCP API服务搜索仓库
    try {
      const repos = await mcpApiService.searchGitHubRepositories(searchQuery.value, githubToken.value)
      console.log(`搜索返回 ${repos.length} 个结果`)
      
      // 过滤掉已存在的项目
      const newRepos = repos.filter(repo => !existingUrls.includes(repo.githubUrl))
      
      progress.value = 100
      status.value = `找到 ${repos.length} 个仓库，其中 ${newRepos.length} 个为新项目`
      
      searchResults.value = newRepos
      totalFound.value = newRepos.length
      
      if (newRepos.length === 0) {
        status.value = '未找到新的AI代理或MCP项目'
      }
      
    } catch (err) {
      console.error('搜索GitHub时出错:', err)
      error.value = '搜索GitHub时出错。请稍后再试。'
    }
    
    isLoading.value = false
    
  } catch (err) {
    handleError(err)
  }
}

const toggleSelect = (index: number) => {
  const idx = selectedIndices.value.indexOf(index)
  if (idx >= 0) {
    selectedIndices.value.splice(idx, 1)
  } else {
    selectedIndices.value.push(index)
  }
}

const handleAddProjects = async () => {
  if (selectedIndices.value.length === 0) {
    ElMessage.warning('请选择要添加的项目')
    return
  }
  
  const selectedProjects = searchResults.value.filter((_, idx) => selectedIndices.value.includes(idx))
  isLoading.value = true
  progress.value = 0
  status.value = '正在添加项目...'
  
  try {
    // 使用McpApiService批量添加选中项目
    const addedProjects = await mcpApiService.addProjects(selectedProjects)
    
    // 更新状态
    importedProjects.value = addedProjects
    importedCount.value = addedProjects.length
    
    // 标记已导入
    localStorage.setItem('has_imported_repos', 'true')
    isFirstImport.value = false
    
    // 显示成功提示
    ElMessage.success(`成功添加 ${addedProjects.length} 个项目`)
    
    // 关闭对话框
    dialogVisible.value = false
    
    // 触发事件
    emit('projects-added', addedProjects)
  } catch (err) {
    handleError(err)
  } finally {
    isLoading.value = false
  }
}

const resetState = () => {
  showResults.value = false
  error.value = null
  searchResults.value = []
  progress.value = 0
  status.value = ''
  selectedIndices.value = []
}

const handleCancel = () => {
  // 如果正在加载，询问用户是否确定要取消
  if (isLoading.value) {
    ElMessageBox.confirm(
      '正在处理中，确定要取消吗？',
      '确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '返回',
        type: 'warning',
      }
    )
      .then(() => {
        dialogVisible.value = false
      })
      .catch(() => {
        // 用户取消关闭
      })
  } else {
    dialogVisible.value = false
  }
}

const handleError = (err: any) => {
  console.error('批量导入出错:', err)
  error.value = '处理请求时出错。请稍后再试。'
  isLoading.value = false
  progress.value = 0
}

const getRepoNameFromUrl = (url: string): string => {
  // 从GitHub URL中提取仓库名
  try {
    const parts = url.split('/')
    const repoName = parts[parts.length - 1] || parts[parts.length - 2] || '未知项目'
    return repoName
  } catch {
    return '未知项目'
  }
}
</script>

<style scoped>
.text-gray-200 {
  color: #e5e7eb;
}
.text-gray-300 {
  color: #d1d5db;
}
.text-gray-400 {
  color: #9ca3af;
}
.border-gray-700 {
  border-color: #374151;
}
.bg-gray-700 {
  background-color: #374151;
}
.text-purple-400 {
  color: #a78bfa;
}

/* 对话框样式 */
:deep(.custom-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #6366F1 0%, #8B5CF6 100%);
  color: white;
  padding: 16px 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.custom-dialog .el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.custom-dialog .el-dialog__body) {
  padding: 24px;
  background-color: #1f2937;
  color: #e5e7eb;
}

:deep(.custom-dialog .el-dialog__footer) {
  background-color: #1f2937;
  border-top: 1px solid #374151;
  padding: 16px 20px;
}

:deep(.custom-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

:deep(.custom-dialog .el-dialog__headerbtn:hover .el-dialog__close) {
  color: #e5e7eb;
}

/* 自定义输入框 */
.custom-input :deep(.el-input__wrapper) {
  background-color: #374151;
  box-shadow: 0 0 0 1px #4b5563;
  border-radius: 6px;
  color: #e5e7eb;
}

.custom-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #6366f1;
}

.custom-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #8b5cf6, 0 0 0 3px rgba(139, 92, 246, 0.3);
}

.custom-input :deep(.el-input__inner) {
  color: #e5e7eb;
}

.custom-input :deep(.el-input__inner::placeholder) {
  color: #9ca3af;
}

/* 自定义按钮 */
.custom-button {
  background: linear-gradient(135deg, #6366F1 0%, #8B5CF6 100%);
  border: none;
  transition: all 0.3s ease;
}

.custom-button:hover {
  background: linear-gradient(135deg, #5a5fea 0%, #7c3aed 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(139, 92, 246, 0.3);
}

.custom-button-secondary {
  background-color: #374151;
  border-color: #4B5563;
  color: #E5E7EB;
  transition: all 0.3s ease;
}

.custom-button-secondary:hover {
  background-color: #4B5563;
  border-color: #6B7280;
  transform: translateY(-1px);
}

/* 自定义弹窗 */
.custom-alert {
  background-color: #1f2937;
  border: 1px solid #374151;
}

:deep(.custom-alert .el-alert__title) {
  color: #e5e7eb;
}

:deep(.custom-alert .el-alert__content) {
  color: #d1d5db;
}

:deep(.custom-alert .el-alert__icon) {
  color: #a78bfa;
}

:deep(.custom-alert.el-alert--success) {
  background-color: rgba(16, 185, 129, 0.1);
  border-color: #059669;
}

:deep(.custom-alert.el-alert--error) {
  background-color: rgba(239, 68, 68, 0.1);
  border-color: #dc2626;
}

/* 自定义滚动条 */
.custom-scrollbar :deep(.el-scrollbar__bar) {
  background-color: #374151;
}

.custom-scrollbar :deep(.el-scrollbar__thumb) {
  background-color: #4b5563;
}

:deep(.el-scrollbar__wrap) {
  background-color: #1f2937;
  border: 1px solid #374151;
  border-radius: 6px;
}

:deep(.el-progress-bar__outer) {
  background-color: #374151;
}

/* 空状态 */
:deep(.el-empty__description) {
  color: #d1d5db;
}
</style>